package controller

import (
	"encoding/xml"
	"fmt"
	"gomptest/model"
	"gomptest/utils"
	"log"
	"time"

	"github.com/gin-gonic/gin"
)

const (
	Token = "ddlasfjkahf"
)

//WXCheckSign 微信签名检查
func WXCheckSign(c *gin.Context) {
	signature := c.Query("signature")
	timestamp := c.Query("timestamp")
	nonce := c.Query("nonce")
	echostr := c.Query("echostr")
	ok := utils.CheckSign(signature, timestamp, nonce, Token)
	if !ok {
		log.Println("error:微信api校验失败")
		return
	}
	log.Println("succes:微信api校验成功")
	//回复，因为是字符串所以用的WriteString
	c.Writer.WriteString(echostr)
}

//WXMsgPost 接收并回复消息
func WXMsgPost(c *gin.Context) {
	var text model.WxTextMsg
	//解析xml并赋值给text
	err := c.ShouldBindXML(&text)
	if err != nil {
		log.Println("error:xml解析失败")
		return
	}
	log.Printf("succes:收到消息：消息类型为%s，消息内容为%s\n", text.MsgType, text.Content)

	repText := model.WxRepTextMsg{
		//因为是发送，所以把接收到的两个值换一下就行了
		ToUserName:   text.FromUserName,
		FromUserName: text.ToUserName,
		CreateTime:   time.Now().Unix(),
		MsgType:      "text",
		Content:      fmt.Sprintf("接收的消息是:%s 回复时间：%s", text.Content, time.Now().Format("2006-01-02 15:04:05")),
	}
	msg, err := xml.Marshal(&repText)
	if err != nil {
		log.Println("error:拼接xml失败")
		return
	}
	//此处因为msg就是byte所以直接用Write
	c.Writer.Write(msg)
}
